package com.neogb.shareringtone;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class Read extends Activity {
	
	private static final int DIALOG_SAVING = 1;
	private Intent mIntent;
	private RingtoneManager mRingtoneManager;
	private Ringtone mRingtone;
	private InputStream mInputStream;
	private Uri mUri;
	private String type;
	private int mediaType = 0;
	private String mfilename = null;
	private String extension = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
	    setContentView(R.layout.read);
	    
	    setProgressBarIndeterminateVisibility(true);
	    
	    mIntent = getIntent();
    	mUri = mIntent.getData();
    	type = mIntent.getType();
    	
    	/*Starting activity: Intent {
    		action=android.intent.action.VIEW
    		data=content://gmail-ls/messages/guillaumebouerat%40gmail.com/44/attachments/0.1/BEST/false
    		type=audio/mpeg
    		flags=0x3880001
    		comp={com.neogb.shareringtone/com.neogb.shareringtone.Read}
    	}*/
    	
	    Thread thread = new Thread() {
			public void run() {
				try {
					mInputStream = getContentResolver().openInputStream(mUri);
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
					showToast(2);
					finish();
				}
				setProgressBarIndeterminateVisibility(false);
			}
		};
		thread.start();
		
		if (type.equals("audio/mpeg") || type.equals("audio/mp3"))
			extension = ".mp3";
		else if (type.equals("audio/wav"))
			extension = ".wav";
		else if (type.equals("audio/ogg") || type.equals("audio/x-ogg"))
			extension = ".ogg";
		
		if (extension == null) {
			showToast(2);
			finish();
		}
    	
		final TextView textview_extention = (TextView) findViewById(R.id.layout_read_extension);
		textview_extention.setText(extension);
		
    	mRingtoneManager = new RingtoneManager(this);
        mRingtoneManager.setStopPreviousRingtone(true);
        mRingtone = RingtoneManager.getRingtone(this, mUri);
        
		final RadioButton radio_alarm = (RadioButton) findViewById(R.id.layout_read_radio_alarm);
		radio_alarm.setOnClickListener(new OnClickListener() {
		    public void onClick(View v) {
		    	if (radio_alarm.isChecked())
		    		mediaType = 1;
		    }
		});
		final RadioButton radio_notification = (RadioButton) findViewById(R.id.layout_read_radio_notification);
		radio_notification.setOnClickListener(new OnClickListener() {
		    public void onClick(View v) {
		    	if (radio_notification.isChecked())
		    		mediaType = 2;
		    }
		});
		final RadioButton radio_ringtone = (RadioButton) findViewById(R.id.layout_read_radio_ringtone);
		radio_ringtone.setOnClickListener(new OnClickListener() {
		    public void onClick(View v) {
		    	if (radio_ringtone.isChecked())
		    		mediaType = 3;
		    }
		});
		
		
		final Button mButtonRead = (Button) findViewById(R.id.layout_read_read);
		mButtonRead.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		if (mButtonRead.isPressed()) {
        			mRingtone.play();
        		}
        	}
        });
		
		final Button mButtonSave = (Button) findViewById(R.id.layout_read_save);
		mButtonSave.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		if (mButtonSave.isPressed()) {
        			final EditText mEditTextFilename = (EditText) findViewById(R.id.layout_read_filename);
        			mfilename = mEditTextFilename.getText().toString();
        			if (mediaType > 0 && mfilename.length() > 0) {
	        			showDialog(DIALOG_SAVING);
	        			Thread thread = new Thread() {
	        				public void run() {
	        					saveRingtone(mInputStream);
	        					mHandler.sendEmptyMessage(1);
	        				}
	        			};
	        			thread.start();
        			}
        			else
        				showToast(2);
        		}
        	}
        });
	
	}
	
	private String setPath() {
		String path = Environment.getExternalStorageDirectory() + "/media/audio/";
		if (mediaType == 1)
			path += "alarms";
		else if (mediaType == 2)
			path += "notifications";
		else if (mediaType == 3)
			path += "ringtones";
		path += "/";
		return path;
	}
	
	private void saveRingtone(InputStream data) {
		
		String path = setPath();
		
		new File(path).mkdirs();
		final File ringtone = new File(path, mfilename + extension);
		
		if (ringtone.exists()) {
			ringtone.delete();
		}
		
		final ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, path + mfilename + extension);
        values.put(MediaStore.MediaColumns.TITLE, mfilename);
        //values.put(MediaStore.MediaColumns.SIZE, "");
        values.put(MediaStore.MediaColumns.MIME_TYPE, type);

        //values.put(MediaStore.Audio.Media.ARTIST, "");
        //values.put(MediaStore.Audio.Media.DURATION, "");

        values.put(MediaStore.Audio.Media.IS_ALARM, mediaType == 1);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, mediaType == 2);
        values.put(MediaStore.Audio.Media.IS_RINGTONE, mediaType == 3);
		
		try {
			final FileOutputStream fos = new FileOutputStream(ringtone.getPath());
			int readBytes;
			while ((readBytes = data.read()) != -1){
				fos.write(readBytes);
			}
			fos.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		
		final Uri uri = MediaStore.Audio.Media.getContentUriForPath(path + mfilename + extension);
		//final Uri newUri = getContentResolver().insert(uri, values);
		getContentResolver().insert(uri, values);
	}
	
	private final Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
        	if (msg.what == 1) {
        		removeDialog(DIALOG_SAVING);
        		showToast(1);
        	}
        }
	};
	
	private void showToast(int nmsg) {
		String msg = "";
		switch (nmsg) {
			case 1:
				msg = getString(R.string.toast_msg_1);
				break;
			case 2:
				msg = getString(R.string.toast_msg_2);
				break;
		}
		final Toast mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
		mToast.show();
	}
	
	@Override
    protected Dialog onCreateDialog(int which) {
        switch (which) {
            case DIALOG_SAVING:
                final ProgressDialog dlg = new ProgressDialog(this);
                dlg.setTitle(getString(R.string.dialog_saving_title));
                dlg.setMessage(getString(R.string.dialog_saving_message));
                return dlg;
        }
        return null;
    }
	
	
}